package com.kingtao.entry;

import com.kingtao.enums.NodeStatusEnums;
import com.kingtao.util.CoreData;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: kingtao
 * @Date: 2023-07-26-16:48
 * @Description:
 */
@Data
public class NodeGroup {

    //  leader
    private volatile int leaderId = 0;

    //  secondLeader
    private volatile int secondLeaderId = 0;

    //  followerLeader
    private volatile Map<Integer, Integer> followerLeaderIdMap;

    //  leader的任期
    private volatile int LeaderCurrentTerm = 0;
    private volatile int SecondLeaderCurrentTerm = 0;

    //  日志索引
    private volatile int LogIndex;

    //  节点组
    private volatile List<Node> nodes;

    public NodeGroup(List<Node> nodes) {
        this.nodes = nodes;
        followerLeaderIdMap = new ConcurrentHashMap<>();
    }

    public void addLeaderCurrentTerm() {
        LeaderCurrentTerm++;
        for (Node n : nodes) {
            n.setLeaderCurrentTerm(LeaderCurrentTerm);
        }
    }

    public void addSecondLeaderCurrentTerm() {
        SecondLeaderCurrentTerm++;
        for (Node n : nodes) {
            n.setSecondLeaderCurrentTerm(SecondLeaderCurrentTerm);
        }
    }

    public NodeGroup() {
        followerLeaderIdMap = new ConcurrentHashMap<>();
    }

    //  通过  Node的id 获取节点
    public Node getNodeByNodeId(int id) {
        for (Node n : nodes) {
            if (n.getId() == id) {
                return n;
            }
        }
        return null;
    }

    //  通过索引获取node
    public Node getNodeByIndex(int index) {
        if (index > nodes.size()) {
            return null;
        }
        return nodes.get(index);
    }

    //  获取所有follower
    public List<Node> getAllFollower() {
        List<Node> followers = new ArrayList<>();
        for (Node node : nodes) {
            if (node.getStatus() == NodeStatusEnums.follower){
                followers.add(node);
            }
        }
        return followers;
    }

    public void addNode(Node node) {
        nodes.add(node);
    }

    public List<Node> getAllFollowerLeader() {
        List<Node> followerLeaderList = new ArrayList<>();
        if (getFollowerLeaderIdMap() != null) {
            for (int i=0; i< CoreData.GROUP_NUM; i++){
                followerLeaderList.add(getNodeByNodeId(followerLeaderIdMap.get(i)));
            }
            return followerLeaderList;
        }
        return null;
    }

    @Override
    public String toString() {
        return "NodeGroup{" +
                "leaderId=" + leaderId +
                ", secondLeaderId=" + secondLeaderId +
                ", followerLeaderIdMap=" + followerLeaderIdMap +
                ", \nLeaderCurrentTerm=" + LeaderCurrentTerm +
                ", \nSecondLeaderCurrentTerm=" + SecondLeaderCurrentTerm +
                ", \nnodes=\n" + nodes +
                '}';
    }
}
